﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using medicine.DAL.DataSet1TableAdapters;
using medicine.BaseComponents.Groups;
using medicine.DAL;
using Microsoft.Office.Interop.Owc11;
using medicine.General;
using System.Data.OleDb;
using System.IO;
using medicine.Forms;
using EventLogger;

namespace medicine
{
    public partial class MainFRM : Form
    {
        private enum PrintingOptions
        {
            Preview,
            Print,
            PageSetup
        }

        private PrintingOptions LastPrintOption { get; set; }

        const string FORM_TEXT = "AMCS Pharma Analyze";

        private bool _DataRetrieved = false;
        private bool _SavedVar = true;
        private bool _Saved
        {
            get { return _SavedVar; }
            set
            {
                _SavedVar = value;
                if (!_SavedVar)
                {
                    if (!this.Text.EndsWith("*"))
                        this.Text += "*";
                }
                else
                    if (this.Text.EndsWith("*"))
                        this.Text = this.Text.Substring(0, this.Text.Length - 1);
            }
        }
        private string OpenFileNameWhenLoading { get; set; }
        private string _FormText
        {
            get
            {
                if (!string.IsNullOrWhiteSpace(this._FileName))
                    return System.IO.Path.GetFileNameWithoutExtension(this._FileName) + " - " + FORM_TEXT;
                else
                    return FORM_TEXT;
            }
        }

        private string _FileNameVar = "";

        private string _FileName
        {
            get
            {
                return _FileNameVar;
            }
            set
            {
                _FileNameVar = value;
                this.Text = this._FormText;
            }
        }
        public MainFRM(string FileName)
            : this()
        {
            this.OpenFileNameWhenLoading = FileName;
        }

        public MainFRM()
        {
                InitializeComponent();
                tabWorksheet.Enabled = false;
                MedicinUtilities.AfterDropComplete += new MedicinUtilities.AfterDropCompleteHandler(MedicinUtilities_AfterDropComplete);
                MedicinUtilities.AfterRowSelection += new MedicinUtilities.AfterRowSelectionHandler(MedicinUtilities_AfterRowSelection);

        }

        void MedicinUtilities_AfterRowSelection(Control Sender)
        {
            _Saved = false;
            EnableDisableRetrieveDataButton();

        }

        void MedicinUtilities_AfterDropComplete(Mover Sender, Control Parent, Control NewParent)
        {
            _Saved = false;
            EnableDisableRetrieveDataButton();

        }


        private void Form1_Load(object sender, EventArgs e)
        {
            this.SuspendLayout();
            MedicinUtilities.InitilizeApplication(Application.ExecutablePath);
            this.tabControl1.TabPages.Remove(tabPage1);
            MedicineDBStructure.Initilize();           
            SetRetrieveDataButtonEnabling(false);
            EnableDisableButtonsWhenRetreiveData(false);
            groupsPanel1.LoadGroupsFromDB();

            FillTable();
            this.Text = this._FormText;

            if (!string.IsNullOrWhiteSpace(this.OpenFileNameWhenLoading))
                OpenQuery(this.OpenFileNameWhenLoading);

            this.ResumeLayout();
        }

        private void FillGroups()
        {

        }

        private void FillTable()
        {
            //DGV.AutoGenerateColumns = false;
            //DGV.DataSource = new DemoTableAdapter().GetData();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void groupsPanel1_Dragging(Control Sender, Rectangle Area)
        {
            ClearDraggingTest();

            foreach (Control item in tabMarket.Controls)
                if (DoDragging(item, Sender, Area))
                    return;

            foreach (Control item in this.Controls)
                if (DoDragging(item, Sender, Area))
                    return;

        }
        private bool DoDragging(Control item, Control Sender, Rectangle Area)
        {
            if (item is IDragDestination)
                if (((IDragDestination)item).TestHitTarget(Sender, Area))
                {
                    ((IDragDestination)item).DragOver();
                    return true;
                }
            return false;
        }


        private Control groupsPanel1_DropTest(Control Sender)
        {

            ClearDraggingTest();
            foreach (Control item in tabMarket.Controls)
            {
                Control Temp = DoDropTest(Sender, item);
                if (Temp != null)
                    return Temp;
            }
            foreach (Control item in this.Controls)
            {
                Control Temp = DoDropTest(Sender, item);
                if (Temp != null)
                    return Temp;
            }

            return null;
        }
        private Control DoDropTest(Control Sender, Control item)
        {
            this.SuspendLayout();
            if (item is IDragDestination)
                if (((IDragDestination)item).TestHitTarget(Sender, new Rectangle(Sender.Location, Sender.Size)))
                {
                    Control NewParent = ((IDragDestination)item).DragDrop((Label)Sender);
                    return NewParent;
                }
            this.ResumeLayout();
            return null;
        }

        private void ClearDraggingTest()
        {
            foreach (Control item in tabMarket.Controls)
            {
                if (item is IDragDestination)
                    ((IDragDestination)item).DragOut();
            }
            foreach (Control item in this.Controls)
            {
                if (item is IDragDestination)
                    ((IDragDestination)item).DragOut();
            }

        }

        private void btnRetreiveData_Click(object sender, EventArgs e)
        {
            OleDbDataReader dr = OleDbUtilities.ExecuteDataReader(MedicineDBStructure.GrandSelectForCount + " WHERE" + MedicinUtilities.GetSQLFilter() + MedicinUtilities.GetPeriodsSQLFilter());

            if (!dr.Read() || (int)dr["RecCount"] == 0)
            {
                MessageBox.Show("No Database Records were Selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            List<UnitsClass> Measures = UnitsClass.ValuesToUnits(MedicinUtilities.GetSpecificColumn("Measures").GroupInfo.Selected);            
            string SelectStatment = MedicineDBStructure.GetGrandSelect(Measures) + " WHERE" + MedicinUtilities.GetSQLFilter() + MedicinUtilities.GetPeriodsSQLFilter();
            List<string> Rows = new List<string>();
            List<PeriodClass> Periods = new List<PeriodClass>();
            
            foreach (GroupLabel item in MedicinUtilities.GetSelectedRowsGroups())
            {
                Rows.Add(item.GroupInfo.DBDisplayField);
            }
            foreach (string item in MedicinUtilities.GetSpecificColumn("Periods").GroupInfo.Selected)
            {
                Periods.Add(PeriodClass.DeSerialize(item));
            }
            OleDbDataReader x = OleDbUtilities.ExecuteDataReader(SelectStatment);
            GridUtil.FillGrid(this.axPivotTable1, this.AxChartSpace2, SelectStatment, Rows, Periods, Measures);
            EnableDisableButtonsWhenRetreiveData(true);

        }

        private void EnableDisableButtonsWhenRetreiveData(bool Enabled)
        {

            this._DataRetrieved = Enabled;
            tabWorksheet.Enabled = Enabled;

            if (Enabled)
                tabControl1.SelectedTab = tabWorksheet;
            else
                tabControl1.SelectedTab = tabMarket;
            printToolStripButton.Enabled = Enabled;
            printToolStripMenuItem.Enabled = Enabled;
            PageSetupMenuItem.Enabled = Enabled;
            worksheetToolStripMenuItem1.Enabled = Enabled;
            printPreviewToolStripMenuItem.Enabled = Enabled;
            ExportToExceltoolStripMenuItem.Enabled = Enabled;
            ExportToExceltoolStripButton.Enabled = Enabled;
            ExportToHTMLtoolStripButton.Enabled = Enabled;
            ExportToHTMLtoolStripMenuItem.Enabled = Enabled;
            totalAcrossToolStripMenuItem.Enabled = Enabled;
            totalDownToolStripMenuItem.Enabled = Enabled;
            rankColumnsToolStripMenuItem.Enabled = Enabled;

        }

        public void EnableDisableRetrieveDataButton()
        {
            if (!string.IsNullOrWhiteSpace(MedicinUtilities.GetSQLFilter()) && MedicinUtilities.GetSelectedRowsGroups().Count > 0 && MedicinUtilities.IsAllColumnsSelected())
            {
                SetRetrieveDataButtonEnabling(true);
            }
            else
            {
                SetRetrieveDataButtonEnabling(false);
            }
            ////return;
            //MessageBox.Show("selected Items\r\n" + MedicinUtilities.GetSQLFilter());
            //string temp = "";
            //foreach (GroupLabel item in MedicinUtilities.GetSelectedRowsGroups())
            //{
            //    temp = temp + "\r\n" + item.GroupInfo.DBTableName;
            //}
            //MessageBox.Show("selected Tables\r\n" + temp);
            //temp = "";
            //foreach (GroupLabel item in MedicinUtilities.ColumnLabels )
            //{
            //    if (item.GroupInfo.isFiltered)
            //        temp = temp + "\r\n" + item.GroupInfo.DBTableName;
            //}
            //MessageBox.Show("Selected Columns\r\n" + temp);

        }

        private void SetRetrieveDataButtonEnabling(bool Enabled)
        {
            if (Enabled)
            {
                btnRetreiveData.BackColor = Color.FromArgb(255, 153, 0);
                btnRetreiveData.ForeColor = Color.FromName(KnownColor.ControlText.ToString());
            }
            else
            {
                btnRetreiveData.BackColor = Color.FromArgb(160, 160, 164);
                btnRetreiveData.ForeColor = Color.FromName(KnownColor.ButtonFace.ToString());
            }
            btnRetreiveData.Enabled = Enabled;
            retrieveDataToolStripMenuItem.Enabled = Enabled;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show(axPivotTable1.HTMLData);
            MessageBox.Show(axPivotTable1.XMLData);
            EnableDisableRetrieveDataButton();
        }

        private void axPivotTable1_Enter(object sender, EventArgs e)
        {

        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            return;
            if (tabControl1.SelectedTab == tabWorksheet && !this._DataRetrieved)
                tabControl1.SelectedTab = tabMarket;
        }

        private void btnShowHideGroups_Click(object sender, EventArgs e)
        {
            this.SuspendLayout();
            if (groupsPanel1.Visible)
            {
                btnShowHideGroups.Text = ">>";
                btnShowHideGroups.Left = 6;
                lblAttribute.Visible = false;
                groupsPanel1.Visible = false;
                tabControl1.Left = 6;
                tabControl1.Width = this.ClientSize.Width - tabControl1.Left;
                btnRetreiveData.Left = btnShowHideGroups.Left + btnShowHideGroups.Width + 6;
            }

            else
            {

                btnShowHideGroups.Text = "<<";
                btnShowHideGroups.Left = 129;
                lblAttribute.Visible = true;
                groupsPanel1.Visible = true;
                tabControl1.Left = groupsPanel1.Left + groupsPanel1.Width + 6;
                tabControl1.Width = this.ClientSize.Width - tabControl1.Left;
                btnRetreiveData.Left = btnShowHideGroups.Left + btnShowHideGroups.Width + 6;
            }
            this.ResumeLayout();
        }

        private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
        {
            TabControl tabControl = sender as TabControl;
            TabPage tabPage = tabControl.TabPages[e.Index];

            if (tabPage.Enabled == false)
            {
                using (SolidBrush brush =
                   new SolidBrush(SystemColors.GrayText))
                {
                    e.Graphics.DrawString(tabPage.Text, tabPage.Font, brush,
                       e.Bounds.X + 3, e.Bounds.Y + 3);
                }
            }
            else
            {
                using (SolidBrush brush = new SolidBrush(tabPage.ForeColor))
                {
                    e.Graphics.DrawString(tabPage.Text, tabPage.Font, brush,
                       e.Bounds.X + 3, e.Bounds.Y + 3);
                }
            }
        }

        private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if (e.TabPage.Enabled == false)
            {
                e.Cancel = true;
            }
        }

        private void saveToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            SaveQueryMnu();
        }
        private bool SaveQueryMnu()
        {
            if (string.IsNullOrWhiteSpace(this._FileName))
            {
                return SaveQueryAs();
            }
            else
            {
                SaveQuery(this._FileName);
                return true;
            }

        }

        private void SaveQuery(string FileName)
        {
            SerializableProjectInfo SPI = new SerializableProjectInfo(MedicinUtilities.ColumnLabels, MedicinUtilities.GroupsLabels);
            SerializingUtility.SerializeObjectToFile<SerializableProjectInfo>(SPI, FileName);
            this._Saved = true;
            this._FileName = FileName;
            //GroupInfo gp = new GroupInfo();
            //SerializingUtility.SerializeObjectToFile<GroupInfo>(gp, @"c:\test.xml");

            //System.Xml.Serialization.XmlSerializer p;

            //MedicinUtilities.ColumnLabels;
            //MedicinUtilities.GroupsLabels;

            //MedicinUtilities.GetSQLFilter();
            //MedicinUtilities.GetSelectedRowsGroups().Count;
            //MedicinUtilities.IsAllColumnsSelected();

        }

        private void openToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //if (!this._Saved)
            if (!ConfirmSaving()) return;

            openFileDialog1.FileName = "";
            if (DialogResult.OK == openFileDialog1.ShowDialog())
            {
                if (!NewQuery()) return;
                OpenQuery(openFileDialog1.FileName);
            }
        }

        private void OpenQuery(string FileName)
        {

            SerializableProjectInfo SPI = SerializingUtility.DeserializeObjectFromFile<SerializableProjectInfo>(FileName);
            GroupLabel Temp;
            SelectedGroup Temp2;
            foreach (GroupInfo item in SPI.ColumnInfo)
            {
                Temp = MedicinUtilities.GetSpecificColumn(item.DBTableName);
                if (Temp != null)
                    Temp.Copy(item);
            }

            foreach (GroupInfo item in SPI.GroupsInfo)
            {
                Temp = MedicinUtilities.GetSpecificGroup(item.Text);
                if (Temp != null)
                {
                    Temp.Copy(item);
                    Temp2 = GetSpecificSelectedGroup(item.SelectedRowOrder);
                    if (Temp2 != null)
                    {
                        Temp2.DragDrop(Temp);
                    }
                }
            }

            groupsPanel1.Redraw();
            EnableDisableRetrieveDataButton();
            this._FileName = FileName;
            //TODO: Activate / decativate (Retrieve) button and other buttons.
        }
        private SelectedGroup GetSpecificSelectedGroup(int order)
        {
            foreach (Control item in tabMarket.Controls)
            {
                if (item is SelectedGroup)
                {
                    if (((SelectedGroup)item).GroupOrder == order)
                    {
                        return (SelectedGroup)item;
                    }
                }
            }
            return null;
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {            
            NewQuery();
        }

        private bool NewQuery()
        {
            if (!ConfirmSaving()) return false;

            EnableDisableButtonsWhenRetreiveData(false);
            groupsPanel1.LoadGroupsFromDB();
            ResetAllSelectedColumns();
            SetRetrieveDataButtonEnabling(false);
            this._Saved = true;
            this._FileName = "";
            saveFileDialog1.FileName = "Untitiled1";
            return true;

        }
        private void ResetAllSelectedColumns()
        {
            foreach (Control item in tabMarket.Controls)
                if (item is SelectedColumns)
                    ((SelectedColumns)item).Reset();
        }

        private void marketToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedTab = tabMarket;
        }

        private void worksheetToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedTab = tabWorksheet;
        }

        private void toolbarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStrip1.Visible = toolbarToolStripMenuItem.Checked;
            ResizeControls();
        }

        private void toolbarToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void statusBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            statusStrip1.Visible = statusBarToolStripMenuItem.Checked;
            ResizeControls();
        }
        private void ResizeControls()
        {
            groupsPanel1.Top = pnlTabs.Bottom + 5;

            if (statusStrip1.Visible)
                groupsPanel1.Height = statusStrip1.Top - groupsPanel1.Top - 2;
            else
                groupsPanel1.Height = this.Height - groupsPanel1.Top - 2;

            tabControl1.Top = groupsPanel1.Top;
            tabControl1.Height = groupsPanel1.Height;
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveQueryAs();
        }

        private bool SaveQueryAs()
        {
            if (DialogResult.OK == saveFileDialog1.ShowDialog())
            {
                SaveQuery(saveFileDialog1.FileName);
                return true;
            }
            else
                return false;
        }

        private void ExportToExceltoolStripMenuItem_Click(object sender, EventArgs e)
        {
            //axPivotTable1.e
            if (DialogResult.OK == ExportToExcelsaveFileDialog.ShowDialog(this))
                axPivotTable1.Export(ExportToExcelsaveFileDialog.FileName, PivotExportActionEnum.plExportActionNone);
        }

        private void printToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.LastPrintOption = PrintingOptions.Print;
            string HtmlData = axPivotTable1.HTMLData;
            webBrowser1.DocumentText = HtmlData;

        }

        void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (this.LastPrintOption == PrintingOptions.Preview)
            {
                ((WebBrowser)sender).ShowPrintPreviewDialog();
            }

            if (this.LastPrintOption == PrintingOptions.Print )
            {
                ((WebBrowser)sender).ShowPrintDialog();
            }
            if (this.LastPrintOption == PrintingOptions.PageSetup)
            {
                ((WebBrowser)sender).ShowPageSetupDialog();
            }
        }

        private bool ConfirmSaving()
        {
            if (!this._Saved)
            {
                DialogResult Res = MessageBox.Show("Query has changed, do you want to save?", "Confirm Saving changes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (DialogResult.Cancel == Res)
                    return false;
                if (DialogResult.Yes == Res)
                {
                    return SaveQueryMnu();
                }
            }
            return true;
        }

        private void MainFRM_FormClosing(object sender, FormClosingEventArgs e)
        {

            if (!ConfirmSaving()) e.Cancel = true;
        }

        public class SerializableProjectInfo
        {
            //public List<GroupLabel> ColumnLabels;
            //public List<GroupLabel> GroupsLabels;
            public List<GroupInfo> ColumnInfo = new List<GroupInfo>();
            public List<GroupInfo> GroupsInfo = new List<GroupInfo>();
            public SerializableProjectInfo()
            {
            }

            public SerializableProjectInfo(List<GroupLabel> ColumnLabels, List<GroupLabel> GroupsLabels)
            {
                //this.ColumnLabels = ColumnLabels;
                //this.GroupsLabels = GroupsLabels;
                foreach (GroupLabel item in ColumnLabels)
                {
                    ColumnInfo.Add(item.GroupInfo);
                }
                foreach (GroupLabel item in GroupsLabels)
                {
                    GroupsInfo.Add(item.GroupInfo);
                }

            }
        }

        private void printPreviewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.LastPrintOption = PrintingOptions.Preview;
            string HtmlData = axPivotTable1.HTMLData;
            webBrowser1.DocumentText = HtmlData;
           
        }

        private void PageSetupMenuItem_Click(object sender, EventArgs e)
        {
            this.LastPrintOption = PrintingOptions.PageSetup;
            string HtmlData = axPivotTable1.HTMLData;
            webBrowser1.DocumentText = HtmlData;
        }

        private void fileToolStripMenuItem1_Click(object sender, EventArgs e)
        {


        }

        private void ExportToHTMLtoolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == ExporToHTMLsaveFileDialog.ShowDialog(this))
            {
                string HtmlData = axPivotTable1.HTMLData;
                SerializingUtility.SaveToTextFile(ExporToHTMLsaveFileDialog.FileName, HtmlData, false);
                SerializingUtility.ShellOpenFile(ExporToHTMLsaveFileDialog.FileName);
            }
        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }


    }
}
